
const CryptoJS = require('../../utils/crypto-js.js')

let clickItemIndex = 0
Page({
  data: {
    itrahost:"https://itra.run",
    colors:['#797B77', '#8BCE3D', '#D1C408', '#5BC9EE','#B16DA7','#DA702E','#B53229'],
    runnerId:"",
    lastName:'',
    firstName:'',
    gender:'',
    nationality:'',
    profilePic:"",
    pi:0,
    data:[],
    page:1,
    list:[],
    loading:false,
    noData:false,
    noMore:false,
    errormsg:'维护中',
    session:'',
    application:'',
    followtext:'',
    favlist:[]
  },
  onLoad:function(options){
    var obj =JSON.parse(decodeURIComponent(options.str))
    console.log(obj);
    this.setData({
      runnerId:obj.runnerId,
      lastName:obj.lastName,
      firstName:obj.firstName,
      gender:obj.gender,
      nationality:obj.nationality,
      profilePic:obj.profilePic,
      pi:obj.pi
    })
    this.initFavList();
  },

  onReady:function(){
    this.runnerinfo()
  },

  raceItem:function(e){
    clickItemIndex = e.currentTarget.dataset.index;
      this.go2Detai();
  },

  onItem:function(e){
    var intdex = e.currentTarget.dataset.index;
    let newList = this.data.list.slice()
    newList[intdex].hidden = !newList[intdex].hidden;
    this.setData({
      list:newList
    })
  },
  initFavList(){
    var listStr = wx.getStorageSync('myfavs');
    if(listStr){
      var fav =JSON.parse(listStr)
      this.setData({
        favlist:fav
      })
    } 
    this.updateFav();
  },

  updateFav(){
    var ruanin = this.data.runnerId;
    var index = this.data.favlist.findIndex(function(item){
        return item.runnerId == ruanin;
    });
    this.setData({
        followtext:index>=0?'1':'0'
    })
  },

  onFollow:function(){
      var ruanin = this.data.runnerId;
      var index = this.data.favlist.findIndex(function(item){
          return item.runnerId == ruanin;
      });
      if(index>=0){
        this.data.favlist.splice(index,1);
      }else{
        var saveinfo = {
          'runnerId':this.data.runnerId,
          'firstName':this.data.firstName,
          'lastName':this.data.lastName,
          'profilePic':this.data.profilePic,
          'gender':this.data.gender,
          'nationality':this.data.nationality,
        };
        this.data.favlist.unshift(saveinfo);
      }
      var strj = JSON.stringify(this.data.favlist);
      wx.setStorageSync('myfavs', strj);
      this.updateFav();
  },

  calculateAveragePace:function(timeStr, distance) {
    if(timeStr==null || timeStr==''|| timeStr=='0') return '';
    const [hours, minutes, seconds] = timeStr.split(':').map(Number);
    const totalSeconds = hours * 3600 + minutes * 60 + seconds;
    const avgSecondsPerKm = totalSeconds / distance;
    const minutes1 = Math.floor(avgSecondsPerKm / 60);
    const secs1 = Math.floor(avgSecondsPerKm % 60);
    return `${minutes1.toString().padStart(2, '0')}'${secs1.toString().padStart(2, '0')}''`;
  },

  calculateAveragePace1:function(timeStr, distance,elevationGain) {
    if(timeStr==null || timeStr==''|| timeStr=='0') return '';
    const [hours, minutes, seconds] = timeStr.split(':').map(Number);
    const totalSeconds = hours * 3600 + minutes * 60 + seconds;
    const newdis = distance+ elevationGain*10.0/1000;
    const avgSecondsPerKm = totalSeconds / newdis;

    const minutes1 = Math.floor(avgSecondsPerKm / 60);
    const secs1 = Math.floor(avgSecondsPerKm % 60);

    return `${minutes1.toString().padStart(2, '0')}'${secs1.toString().padStart(2, '0')}''`;
  },

   getWeekday(dateString) {
    const [year, month, day] = dateString.split('-').map(Number);
    const date = new Date(year, month - 1, day);
    const dayIndex = date.getDay();
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    return weekdays[dayIndex];
  },

  go2Detai:function(){
    var obj = this.data.list[clickItemIndex];
    var info = {
      'itraPoints':obj.ItraPoint,
      'raceYearId':obj.RaceYearId
    };
    var str = encodeURIComponent(JSON.stringify(info));
    wx.navigateTo({
      url: '../races/races?str='+str
    })
  },

  runnerinfo:function(e){
    var that = this;
    const app = getApp();
    wx.request({
      url: app.globalData.itra_info,
      method:"GET",
      success:(res)=>{
        var response = res.data;
        console.log(response);
        var session = response.Session;
        var application = response.Application;
        that.setData({
          session: session,
          application:application
        });
        that.queryItraDataBack();
        that.resultITRAPrefData();
      },
      fail: (err) => {
        this.setData({
          isLoading: false
        });
        wx.showModal({
          title: '温馨提示',
          content: "网络较慢,数据请求失败!",
          showCancel:false,
          confirmText:"确定",
          confirmColor:"#000000"
        })
      }
    })
},

queryItraDataBack:function(){
  var that = this;
  const app = getApp();
  wx.request({
    url: app.globalData.dataRunnerUrl+this.data.runnerId,
    header:{
      "Accept-Encoding": "gzip, deflate, br",
      "Accept": "*/*",
      "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
      "Connection": "keep-alive",
      'Cookie': '.AspNetCore.Session='+this.data.session+'; .AspNetCore.Identity.Application='+this.data.application
    },
    method:"GET",
    success:(res)=>{
      var results = res.data;
      var id = results.id;
      console.log(results);
      that.setData({
        isLoading:false,
      })
      if (id!=null && id!='') {
          var score = results['pi'];
          var profilePicture = results['profilePicture'];
          var profilePic = profilePicture!=null?'https://itra.run/Files/Photos/'+profilePicture:null;
          that.setData({
            pi:score,
            firstName:results['firstName'],
            lastName:results['lastName'],
            profilePic:profilePic,
            gender:results['gender'],
            nationality:'https://itra.run/images/CountryFlags/'+results['code']+'.svg',
          })
      }else{
        app.refreshToken();
      }
    },
    fail: (err) => {
      this.setData({
        isLoading: false
      });
      wx.showModal({
        title: '温馨提示',
        content: "网络较慢,数据请求失败!",
        showCancel:false,
        confirmText:"确定",
        confirmColor:"#000000"
      })
    }
  })
},

  

  onScrollToLower: function() {
    if(this.data.noMore) return;
    if(this.data.loading) return;
    this.data.page = this.data.page+1;
    this.setData({
      loading:true,
    })
    this.resultITRAPrefData();
  },

  resultITRAPrefData:function(){
    const app = getApp();
    console.log("==备用🔗请求="+this.data.runnerId);
    this.setData({
      loading:true,
    })
    var that = this;
    wx.request({
      url: app.globalData.mineData,
      data:{
        "runnerId":this.data.runnerId,
        "pageNumber":this.data.page,
        "pageSize":"10"
      },
      header:{
        "Accept-Encoding": "gzip, deflate, br",
        "Accept": "*/*",
        "Content-Type": "application/json; charset=UTF-8",
        "Connection": "keep-alive",
        'Cookie': '.AspNetCore.Session='+this.data.session+'; .AspNetCore.Identity.Application='+this.data.application
      },
      method:"GET",
      success:(res)=>{
        var response = res.data;
        // console.log(response)
        var ciphertext_b64 = response.response1;
        if(ciphertext_b64.length!=0){
          var iv_b64 = response.response2;
          var key_b64 = response.response3;
          const key = CryptoJS.enc.Base64.parse(key_b64);
          const iv = CryptoJS.enc.Base64.parse(iv_b64);
          const ciphertext = CryptoJS.enc.Base64.parse(ciphertext_b64);
          const decrypted = CryptoJS.AES.decrypt(
              { ciphertext: ciphertext },
              key,
              {
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
              }
            );
          const plaintext = decrypted.toString(CryptoJS.enc.Utf8);
          // console.log(plaintext)
          const jsonData = JSON.parse(plaintext);
            var results = jsonData.RaceResults;
            this.setData({
              loading:false
            })

          if(results.length>0){
            const newlist = results.map(item=>{
              const averagePace = this.calculateAveragePace(item.Time, item.Distance);
              item.averagePace = averagePace;
              const maxPace = this.calculateAveragePace1(item.Time,item.Distance,item.ElevationGain);
              item.maxPace = maxPace;
              item.week = this.getWeekday(item.Date);
              item.dnf = item.dNF;
              item.hidden = true;
              return item;
            });

            this.setData({
              list:this.data.list.concat(newlist),
              })
            }
            this.setData({
              noMore:results.length<10,
            });
        }else{
          this.setData({
            noData:true,
            loading:false,
          })
        }
      },
      fail: (err) => {//请求失败
        wx.showModal({
          content: "网络较慢,数据请求失败,确定重试吗?",
          confirmText:"确定",
          cancelText:"取消",
          confirmColor:"#000000",
          success: function (res) {
            if (res.cancel) {
               //点击取消,默认隐藏弹框
               wx.navigateBack();
            } else {
               //点击确定
               that.resultITRAPrefData();
            }
         }
        })
      }
    })
},

  onPointClick:function(e){
    wx.showModal({
      content: "小程序非官方，单场表现分请访问官网付费订阅后查看，官网地址：https://itra.run",
      showCancel:false,
      confirmText:"确定",
      confirmColor:"#000000"
    })
  },
  onShareAppMessage:function(){
    var name = this.data.lastName+" "+this.data.firstName+", ITRA表现分:"+this.data.pi;
    return {
        path:"pages/index/index",
        title: name+",来看看你的越野表现如何"
    };
  },
  onShareTimeline:function(){
    var name = this.data.lastName+" "+this.data.firstName+", ITRA表现分:"+this.data.pi;
    return {
      path:"pages/index/index",
      title: name+",来看看你的越野表现如何"
    };
  },
  onShare:function(){
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: [url], // 必须传入数组，即使只有一张图片
      current: url, // 当前显示图片的URL（可选）
    });
  },
  copyPage(){
    var url = 'https://itra.run/RunnerSpace/'+this.data.lastName+'.'+this.data.firstName+'/'+this.data.runnerId;
    wx.setClipboardData({
      data: url,
      success (res) {
        wx.showToast({
          title: 'ITRA个人主页地址已复制',
          icon:"none",
          duration:2500
        })
      }
    })
  },
  goWebView(){
    var url = ''+this.data.runnerId;
    wx.setClipboardData({
      data: url,
      success (res) {
        wx.showToast({
          title: 'ITRA ID已复制',
          icon:"none",
          duration:2500
        })
      }
    })
  },
}
)
